// ActionScript file
import Modules.Security.Users;
import Modules.Windows.ValidationErrorWin;

import com.desidea.common.CommonClass;
import com.desidea.utils.DirtyChecker;
import com.desidea.utils.IDirtyChecker;
import com.desidea.webservice.PartnerService;
import com.desidea.webservice.ProcessServiceRequestResultEvent;

import flash.display.DisplayObject;

import mx.controls.Alert;
import mx.controls.LinkButton;
import mx.managers.PopUpManager;
import mx.rpc.events.FaultEvent;
import mx.utils.StringUtil;
import mx.validators.Validator;

private var _btnEditCancel:LinkButton;
private var _key:String = "";
public var  _caller:DisplayObject;

private var usrDetails:XML;

public function get key():String{
	return _key;
}
public function set key(value:String):void{
	_key = value;
}

public function get caller():DisplayObject{
	return _caller;
}
public function set caller(value:DisplayObject):void{
	_caller = value;
}



private function windowCreated():void{
	this.loadData();
	this.txtFirstName.setFocus();
}

private function init():void{
}

private function onClick(mode:String):void{
	switch(mode){
		case "save":
			handleSave();
			break;
		case "cancel":
			handleCancel();
			break;
	}
}

private function handleCancel():void{
	PopUpManager.removePopUp(this);
}

private function loadData():void{
	if( DirtyChecker.getInstance().isDirty){
		if (DirtyChecker.getInstance().sourceContainer is IDirtyChecker){
			(DirtyChecker.getInstance().sourceContainer as IDirtyChecker).promptToSave();
		}else{
			Alert.show("Save & Proceed");
		}
		return;
	}else{
		DirtyChecker.getInstance().resetDirtyChecker();
	}
	
	
	var params:String = "OPERATION=USERS_GETDETAILS" +
						"&PKID=" + escape(StringUtil.trim(this.key));

	var ws:PartnerService = new PartnerService();
	ws.addprocessServiceRequestEventListener(callForUserDetails);
	ws.addPartnerServiceFaultEventListener(partnerServiceFaultHandler);
	ws.processServiceRequest(params);
	
//	BusySpinner.getInstance().play(Application.application.ModuleCvs);
}

private function callForUserDetails(event:ProcessServiceRequestResultEvent):void{
//	BusySpinner.getInstance().stop();	
	usrDetails = XML(event.result);
//	Alert.show(cntctdetails.toString());
	if(usrDetails.RESPONSE.RESULT == "E"){
		Alert.show(usrDetails.RESPONSE.MESSAGE);
	}else if(usrDetails.RESPONSE.RESULT == 'S'){
		setDataOnControls(usrDetails);
	}
//	else{
//		Alert.show("Unknow Error: Unable to load response");
//	}
}

private function partnerServiceFaultHandler(event:FaultEvent):void{
//	BusySpinner.getInstance().stop();
	Alert.show(event.fault.toString());
}

private function setDataOnControls(response:XML):void{
	cmbDivision.dataProvider = new XML(response.DIVISIONS).entry as XMLList;
	cmbDivision.selectedItem = (response.DIVISIONS.entry.(@id == response.PARTNERDIVISIONID)[0]) as XML;
	cmbDivision.selectedIndex = (cmbDivision.selectedIndex <0)?0:cmbDivision.selectedIndex;
	
//	cmbManager.dataProvider = new XML(response.MANAGERS).entry as XMLList;
//	cmbManager.selectedItem = (response.MANAGERS.entry.(@id == response.MANAGERID)[0]) as XML
//	cmbManager.selectedIndex = (cmbManager.selectedIndex <0)?0:cmbManager.selectedIndex;
	
	CommonClass.setDataOnComponents(this.txtFirstName, response);
	CommonClass.setDataOnComponents(this.txtLastName, response);
	CommonClass.setDataOnComponents(this.txtLoginId, response);
	CommonClass.setDataOnComponents(this.txtPassword, response,true);
	CommonClass.setDataOnComponents(this.chkActive, response);
	CommonClass.setDataOnComponents(this.chkCreateParentAccount, response);
	CommonClass.setDataOnComponents(this.chkEditProductMaster, response);
	CommonClass.setDataOnComponents(this.chkSuperUser, response);
	
	this.txtLoginId.enabled = (this.txtLoginId.text.length == 0);
}

private function getPostData():String{
	var postData:String = new String();

	postData += "USERNO=" + (usrDetails.USERNO.toString())				+ "&";
	postData += "USERGUID=" + (usrDetails.USERGUID.toString())			+ "&";

	postData += (CommonClass.preparePostString(this.txtFirstName))		+ "&";
	postData += (CommonClass.preparePostString(this.txtLastName))		+ "&";

	postData += (CommonClass.preparePostString(this.txtLoginId))		+ "&";
	postData += (CommonClass.preparePostString(this.txtPassword,true))	+ "&";
	postData += (CommonClass.preparePostString(this.chkActive))			+ "&";

	postData += (CommonClass.preparePostString(this.chkCreateParentAccount))	+ "&";
	postData += (CommonClass.preparePostString(this.chkEditProductMaster))		+ "&";
	postData += (CommonClass.preparePostString(this.chkSuperUser))				+ "&";

	postData += "USERID=" + (CommonClass.UserID);

	return postData;	
}

private function handleSave():void{
	if(validate()){
		saveData("",getPostData());
	}
}

private function saveData(action:String, data:String=""):void{
	var params:String = "OPERATION=USERS_UPDATEDETAILS" +
						(data.length>0?"&":"") +data;

	var ws:PartnerService = new PartnerService();
	ws.addprocessServiceRequestEventListener(callForUpdateUserDetails);
	ws.processServiceRequest(params);
	
//	BusySpinner.getInstance().play(Application.application.CMDWindow);
}

private function callForUpdateUserDetails(event:ProcessServiceRequestResultEvent):void{
	
	var response:XML = XML(event.result);
//	BusySpinner.getInstance().stop();
	
	if(response.RESPONSE.RESULT == "S"){
		DirtyChecker.getInstance().resetDirtyChecker();
		
		if(_caller != null){
			(_caller as Users).loadData();
		}
		onClick('cancel');
	}else{
		Alert.show( String(response.RESPONSE.MESSAGE), "Save Error" );	
	}	
}

private function validate():Boolean{
	var v:Array = new Array();
	v.push(fnameV,lnameV, divisionV);
	v.push(loginV, passwordV);
	
	var result:Array = Validator.validateAll(v);

	if(result.length>0){
		var vWin:ValidationErrorWin = new ValidationErrorWin();
		vWin.Messages = result;
		vWin.title = "Save : User Details";
		
		PopUpManager.addPopUp(vWin,this,true);
		PopUpManager.centerPopUp(vWin);
		return false;
	}
	return true;
}